package com.itheima.controller;

import com.alibaba.druid.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.entry.User;
import com.itheima.pojo.R;
import com.itheima.service.UserService;
import com.itheima.utils.SMSUtils;
import com.itheima.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
     private StringRedisTemplate redisTemplate;

    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpSession session) throws Exception {
        String phone = user.getPhone();
        if (!StringUtils.isEmpty(phone)) {
            String code = ValidateCodeUtils.generateValidateCode(4).toString();
            log.info("code={}",code);
            redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);
            //SMSUtils.sendMessage("阿里云短信测试", "SMS_154950909", phone, code);
            //session.setAttribute(phone, code);
            return R.success("验证码发送成功");
        }
        return R.error("发送失败");
    }
    @PostMapping("/login")
    public R<User> login(@RequestBody User user, HttpSession session) throws Exception {
        String phone = user.getPhone();
        String code = user.getCode().toString();
        String attribute = redisTemplate.opsForValue().get(phone);
        //Object attribute = session.getAttribute(phone);
        if (code.equals(attribute) && attribute!=null) {
            LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
            userLambdaQueryWrapper.eq(User::getPhone,phone);
            User one = userService.getOne(userLambdaQueryWrapper);
            if (one==null){
                User user1 = new User();
                user1.setPhone(phone);
                userService.save(user1);
                session.setAttribute("user",user1.getId());
                return R.success(user1);
            }else {
                if (one.getStatus()!=0){
                    return R.error("您被ban了");
                }
            }
            session.setAttribute("user",one.getId());
            redisTemplate.delete(phone);
            return R.success(one);
        }
        return R.error("发送失败");
    }
}
